<?php

namespace App\Http\Middleware;

use App\Admin\Models\SiteCompany;
use App\Store\Models\Account\SiteStore;
use App\Store\Services\Log\LogDoing;
use Closure;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class Accountislogin
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        ini_set('memory_limit', -1);

        $token = $request->header('storetoken');
        $accountinfo = Redis::get($token);
        $accountinfo = $accountinfo ? json_decode($accountinfo, true) : '';

        if (!is_array($accountinfo)) {
            return response()->json([
                'code' => 401, 'msg' => '登录失效，请重新登录'
            ], 200);
        } else {
            if (isset($accountinfo['id']) && isset($accountinfo['cp_id'])) {
                $storetokenbyidlist = Redis::get('store_user_token_list_' . $accountinfo['id']);
                $storetokenbyidlist = json_decode($storetokenbyidlist, true);
                $storetokenbyidlist = is_array($storetokenbyidlist) ? $storetokenbyidlist : [];

                $storetokenbyidlist_bywxapp = Redis::get('store_user_bywxapp_token_list_' . $accountinfo['id']);
                $storetokenbyidlist_bywxapp = json_decode($storetokenbyidlist_bywxapp, true);
                $storetokenbyidlist_bywxapp = is_array($storetokenbyidlist_bywxapp) ? $storetokenbyidlist_bywxapp : [];

                $storetokenbyidlist = array_merge($storetokenbyidlist, $storetokenbyidlist_bywxapp);
                if (!is_array($storetokenbyidlist) || !in_array($token, $storetokenbyidlist)) {
                    return response()->json([
                        'code' => 401, 'msg' => '登录失效，请重新登录!'
                    ], 200);
                }
            } else {
                return response()->json([
                    'code' => 401, 'msg' => '登录失效，请重新登录!!'
                ], 200);
            }

            //判断是否试用，以及试用到期
            //如果是门店店长或店员，判断门店是否到期，其他角色不判断
            if (in_array($accountinfo['type'], [1, 2]) && isset($accountinfo['store_ids']) && intval($accountinfo['store_ids']) > 0) {

                //  $time = Redis::get('store_timeout_at_byid_' . intval($accountinfo['store_ids']));
                //如果未找到门店到期时间缓存则手动查询
//                if ($time <= 0) {
//                    $time = SiteStore::where(['id' => intval($accountinfo['store_ids'])])->value('contract_end_at');
//                    Redis::set('store_timeout_at_byid_' . intval($accountinfo['store_ids']), intval($time));
//                }

                $time = SiteStore::where(['id' => intval($accountinfo['store_ids'])])->value('contract_end_at');

                if ($time < time()) {
                    return response()->json([
                        'code' => 401, 'msg' => '门店已到期，无法使用'
                    ], 200);
                }
                Redis::set('store_timeout_at_byid_' . intval($accountinfo['store_ids']), intval($time));
            }
            $endTime = $request->input('end_time', '');

            if (!empty($endTime)) {
                $request->merge(['end_time' => $this->dateFormat($endTime)]);

            }

            $date_end = $request->input('date_end', '');
            if (!empty($date_end)) {
                $request->merge(['date_end' => $this->dateFormat($date_end)]);
            }

            $order_at_end = $request->input('order_at_end', '');
            if (!empty($order_at_end)) {
                $request->merge(['order_at_end' => $this->dateFormat($order_at_end)]);
            }


            $res = $next($request);
            LogDoing::savelog($request);//记录日志
            $is_locked = Redis::get('LOCKINFO_' . $accountinfo['cp_id']);
            if (intval($is_locked) <= 0) {
                $is_locked = SiteCompany::where(['id' => $accountinfo['cp_id']])->value('is_locked');
                Redis::set('LOCKINFO_' . $accountinfo['cp_id'], $is_locked);
            }

            $content = $res->getContent() ? json_decode($res->getContent(), true) : '';
            if (is_array($content)) {
                if (isset($content['msg'])) {
                    if (strpos($content['msg'], 'Data too long for column') !== false || strpos($content['msg'], 'Out of range value for column') !== false) {
                        return response()->json([
                            'code' => '001', 'msg' => '您的输入已超出限制，请重新输入！'
                        ]);
                    }
                }

                $content['is_locked'] = $is_locked;

                $res->setContent(json_encode($content));
            }


            // Log::info($res->getContent());
            //在此处加字段过滤
            return $res;
        }
    }

    /**
     * 时间处理
     * @param $date
     * @return false|int|string
     */
    public function dateFormat($date)
    {
        if (is_numeric($date)) {
            $date = date("Y-m-d", $date);
            $date = sprintf('%s %s', $date, '23:59:59');
            $date = strtotime($date);
        } else {
            $date = sprintf('%s %s', $date, '23:59:59');
        }
        return $date;
    }
}
